mod expression;

use crate::lexer_mod::token::Token;
use crate::lexer_mod::token_type_enum::Compared;
use crate::lexer_mod::token_type_enum::KeyWord;
use crate::lexer_mod::token_type_enum::Operator;
use crate::lexer_mod::token_type_enum::TokenType;
use crate::lexer_mod::{self, token};
use crate::lexer_mod::{ErrInfo, token_type_enum};

use crate::parser_mod::expression::AccessTarget;
use crate::parser_mod::expression::Expression;
use crate::parser_mod::expression::ExpressionType;
use crate::parser_mod::expression::Parameter;
use crate::parser_mod::expression::Statement;
use crate::parser_mod::expression::Statement::Variable;
use crate::parser_mod::expression::Type;
use rand::distr::Open01;
use rand::rand_core::block;
use std::any::type_name;
use std::ops::Add;
use std::{string, vec};

pub struct Parser {
    pub tokens: Vec<lexer_mod::token::Token>,
    pub errors: Vec<lexer_mod::ErrInfo>,
    pub doc: Vec<String>,
    last_token_line: i32,
    last_token_row: i32,
}

impl Parser {
    pub fn new(mut tokens: Vec<lexer_mod::token::Token>) -> Parser {
        tokens.reverse();
        Parser {
            tokens,
            errors: vec![],
            doc: vec![],
            last_token_line: 0,
            last_token_row: 0,
        }
    }
    fn get_priority(operator: &Operator) -> u8 {
        match operator {
            Operator::Mul => 1,
            Operator::Div => 1,
            Operator::ShiftRight => 1,
            Operator::ShiftLeft => 1,
            Operator::Add => 0,
            Operator::Sub => 0,
            Operator::Assignment => 0,
            Operator::Negate => 0,
            Operator::Any => 0,
        }
    }
    ///不匹配具体的值
    fn try_next_token_variant(&mut self, token: TokenType) -> Option<Token> {
        if let Some(result) = self.tokens.last() {
            if std::mem::discriminant(&token) == std::mem::discriminant(&result.token_type) {
                let result = self.tokens.pop();

                if let Some(token) = &result {
                    self.last_token_row = token.row.clone();
                    self.last_token_line = token.line.clone();
                }
                return result;
            }
        }
        None
    }
    ///类型匹配且移动至下一个Token
    fn try_next_token_is_operator(&mut self, priority: u8) -> bool {
        if let Some(result) = self.tokens.last() {
            if let TokenType::Operator(oper) = &result.token_type {
                let p = Self::get_priority(&oper);
                if p == priority {
                    return true;
                }
            }
        }
        false
    }
    ///类型匹配且移动至下一个Token
    fn try_get_next_token_is_operator(&mut self) -> Option<u8> {
        if let Some(result) = self.tokens.last() {
            if let TokenType::Operator(oper) = &result.token_type {
                let p = Self::get_priority(&oper);
                return Some(p);
            }
        }
        None
    }
    ///类型匹配且移动至下一个Token
    fn try_next_token(&mut self, token: TokenType) -> bool {
        if let Some(result) = self.tokens.last() {
            if &token == &result.token_type {
                let result = self.tokens.pop();

                if let Some(token) = &result {
                    self.last_token_row = token.row.clone();
                    self.last_token_line = token.line.clone();
                }
                return true;
            }
        }
        false
    }
    ///移动至下一个Token
    fn next_token(&mut self) -> Option<Token> {
        let result = self.tokens.pop();

        if let Some(token) = &result {
            self.last_token_row = token.row.clone();
            self.last_token_line = token.line.clone();
        }

        result
    }
    ///只取值,不处理右边的操作符
    pub fn parse_primary(&mut self) -> Option<Expression> {
        while let Some(root_token) = self.next_token() {
            match root_token.token_type {
                //不递归处理右右边的操作符,主要是因为不知道左边的操作符,也不用知道。
                TokenType::ConstString(str) => {
                    return Some(self.new_exp(ExpressionType::ConstString(str)));
                }
                TokenType::ConstFloat(float) => {
                    return Some(self.new_exp(ExpressionType::ConstFloat(float)));
                }
                TokenType::ConstNumber(num) => {
                    return Some(self.new_exp(ExpressionType::ConstNum(num)));
                }
                TokenType::ConstLong(long) => {
                    return Some(self.new_exp(ExpressionType::ConstLong(long)));
                }
                TokenType::ConstLongLong(longlong) => {
                    return Some(self.new_exp(ExpressionType::ConstLongLong(longlong)));
                }
                TokenType::ArrayBegin => {
                    let result = self.parse_array_init()?;
                    return Some(result);
                }
                TokenType::ConstBool(bool) => {
                    return Some(self.new_exp(ExpressionType::ConstBool(bool)));
                }
                //这里就有必要递归取值了，(当作一个新的优先级解析。
                TokenType::FuncBegin => {
                    let result = self.parse()?;
                    if self.try_next_token(TokenType::FuncEnd) {
                        return Some(result);
                    } else {
                        return self.try_parse_operator(result);
                    }
                }
                TokenType::Operator(Operator::Negate) => {
                    let result = self.parse_monomial(Operator::Negate);
                    return self.try_parse_operator(result?);
                }
                TokenType::Operator(Operator::Sub) => {
                    let result = self.parse_monomial(Operator::Sub);
                    return self.try_parse_operator(result?);
                }

                // <Type> <VarName> <操作符> 初始化
                // <Type> <操作符>           操作
                // <VarName>                变量引用
                TokenType::Identifier(str) => {
                    if self.try_next_token(TokenType::FuncBegin) {
                        let result = self.parse_call_function(None, str)?;
                        //这里要递归是因为这里是一个完整的表达式入口。
                        return self.try_parse_operator(result);
                    } else {
                        if let Some(result) =
                            self.try_next_token_variant(TokenType::Identifier("".to_string()))
                        {
                            return None;
                        } else {
                            let result = self.new_exp(ExpressionType::VariableRead {
                                var_name: AccessTarget::Variable(str),
                            });
                            //这里也是，明确了当前是表达式入口就可以递归
                            return self.try_parse_operator(result);
                        }
                    }
                }
                _ => {}
            }
        }
        self.push_err("parse primary时解析函数解析错误,未知原因".to_string());
        None
    }
    ///遇到常量时自动进入递归解析表达式
    pub fn parse(&mut self) -> Option<Expression> {
        while let Some(root_token) = self.next_token() {
            match root_token.token_type {
                TokenType::ConstDeduceNum => {
                    return Some(self.new_exp(ExpressionType::ConstDeduceNum));
                }
                TokenType::ConstString(str) => {
                    let result = self.new_exp(ExpressionType::ConstString(str));
                    return Some(self.try_parse_operator(result)?);
                }
                TokenType::ConstNumber(num) => {
                    let result = self.new_exp(ExpressionType::ConstNum(num));
                    return Some(self.try_parse_operator(result)?);
                }
                TokenType::ConstFloat(float) => {
                    let result = self.new_exp(ExpressionType::ConstFloat(float));
                    return Some(self.try_parse_operator(result)?);
                }
                TokenType::ConstLong(long) => {
                    let result = self.new_exp(ExpressionType::ConstLong(long));
                    return Some(self.try_parse_operator(result)?);
                }
                TokenType::ConstLongLong(longlong) => {
                    let result = self.new_exp(ExpressionType::ConstLongLong(longlong));
                    return Some(self.try_parse_operator(result)?);
                }
                TokenType::ConstBool(bool) => {
                    return Some(self.new_exp(ExpressionType::ConstBool(bool)));
                }
                TokenType::CommentDoc(doc) => {
                    self.doc.push(doc);
                }
                TokenType::ArrayBegin => {
                    let result = self.parse_array_init()?;
                    return Some(result);
                }
                TokenType::FuncBegin => {
                    let result = self.parse()?;
                    if self.try_next_token(TokenType::FuncEnd) {
                        return self.try_parse_operator(result);
                    } else {
                        return self.try_parse_operator(result);
                    }
                }
                //变量定义，注意这里的定义是内置类型的定义
                TokenType::VarType(str) => {
                    if self.try_next_token(TokenType::ArrayBegin) {
                        let token = self.next_token()?;
                        if let TokenType::ConstNumber(num) = token.token_type {
                            if (self.try_next_token(TokenType::ArrayEnd)) {
                                if let Some(result) = self
                                    .try_next_token_variant(TokenType::Identifier("".to_string()))
                                {
                                    if let TokenType::Identifier(var_name) = result.token_type {
                                        let result = self.parse_array_variable_init(
                                            str,
                                            var_name,
                                            Some(num),
                                        );
                                        return result;
                                    }
                                }
                            }
                        } else if let TokenType::ConstDeduceNum = token.token_type {
                            if self.try_next_token(TokenType::ArrayEnd) {
                                if let Some(result) = self
                                    .try_next_token_variant(TokenType::Identifier("".to_string()))
                                {
                                    if let TokenType::Identifier(var_name) = result.token_type {
                                        let result =
                                            self.parse_array_variable_init(str, var_name, None);
                                        return result;
                                    }
                                }
                            }
                        }
                    } else if let Some(result) =
                        self.try_next_token_variant(TokenType::Identifier("".to_string()))
                    {
                        if let TokenType::Identifier(var_name) = result.token_type {
                            let result = self.parse_variable_init(str, var_name);
                            return result;
                        } else {
                            return None;
                        }
                    }
                    self.push_err("变量初始化,非预期标识符".to_string());
                    return None;
                }

                // <Type> <VarName> <操作符> 初始化
                // <Type> <操作符>           操作
                // <VarName>                变量引用
                TokenType::Identifier(str) => {
                    //数组
                    if self.try_next_token(TokenType::ArrayBegin) {
                        let token = self.next_token()?;
                        if let TokenType::ConstNumber(num) = token.token_type {
                            if self.try_next_token(TokenType::ArrayEnd) {
                                if let Some(result) = self
                                    .try_next_token_variant(TokenType::Identifier("".to_string()))
                                {
                                    if let TokenType::Identifier(var_name) = result.token_type {
                                        let result = self.parse_array_variable_init(
                                            str,
                                            var_name,
                                            Some(num),
                                        );
                                        return result;
                                    }
                                }
                            }
                        } else if let TokenType::ConstDeduceNum = token.token_type {
                            if self.try_next_token(TokenType::ArrayEnd) {
                                if let Some(result) = self
                                    .try_next_token_variant(TokenType::Identifier("".to_string()))
                                {
                                    if let TokenType::Identifier(var_name) = result.token_type {
                                        let result =
                                            self.parse_array_variable_init(str, var_name, None);
                                        return result;
                                    }
                                }
                            }
                        }
                    }
                    if self.try_next_token(TokenType::FuncBegin) {
                        let result = self.parse_call_function(None, str)?;
                        //递归引用
                        return self.try_parse_operator(result);
                        //int[];
                    } else {
                        if let Some(result) =
                            self.try_next_token_variant(TokenType::Identifier("".to_string()))
                        {
                            if let TokenType::Identifier(var_name) = result.token_type {
                                let result = self.parse_variable_init(str, var_name);
                                return result;
                            }
                        } else {
                            let result = self.new_exp(ExpressionType::VariableRead {
                                var_name: AccessTarget::Variable(str),
                            });
                            //递归引用
                            return self.try_parse_operator(result);
                        }
                    }
                }

                TokenType::KeyWord(key_word) => match key_word {
                    KeyWord::Null => {
                        return Some(self.new_exp(ExpressionType::Null));
                    }
                    KeyWord::Return => {
                        if self.try_next_token(TokenType::Semicolon) {
                            return Some(self.new_exp(ExpressionType::Return { value: None }));
                        } else {
                            let right = self.parse()?;
                            return Some(self.new_exp(ExpressionType::Return {
                                value: Some(Box::new(right)),
                            }));
                        }
                    }
                    //
                    KeyWord::If => {
                        return self.parse_if();
                    }
                    KeyWord::Func => {
                        let mut func_name: String = String::new();

                        let token_2 = self.next_token()?;
                        if let TokenType::Identifier(string) = token_2.token_type {
                            func_name = string;
                        } else {
                            self.push_err(format!("函数定义错误,非预期标识符 {:?}", token_2));
                            return None;
                        };

                        let token_2 = self.next_token()?;
                        if let TokenType::FuncBegin = token_2.token_type {
                            return self.parse_function(func_name);
                        } else {
                            self.push_err(format!("函数定义错误,非预期标识符 {:?}", token_2));
                            return None;
                        };
                    }
                    KeyWord::Class => {
                        let mut class_name: String = String::new();

                        let token_2 = self.next_token()?;
                        if let TokenType::Identifier(string) = token_2.token_type {
                            class_name = string;
                        } else {
                            self.push_err(format!("类型定义错误,非预期标识符 {:?}", token_2));
                            return None;
                        };
                        if self.try_next_token(TokenType::BlockBegin) {
                            return self.parse_class(class_name.as_str());
                        } else {
                            self.push_err("类型定义错误,非预期标识符".to_string());
                            return None;
                        }
                    }
                    KeyWord::For => {
                        return self.parse_for();
                    }
                    KeyWord::While => {
                        return self.parse_while();
                    }
                    _ => {
                        self.push_err(format!("解析错误,非预期标识符 {:?}", key_word));
                        return None;
                    }
                },
                TokenType::BlockBegin => {
                    return self.parse_block();
                }
                _ => {
                    self.doc.clear();
                }
            }
        }
        self.push_err("parse 时函数解析错误,未知原因".to_string());
        None
    }
    fn get_var_type(type_name: &str) -> Type {
        match type_name {
            "none" => Type::None,
            "int" => Type::Int,
            "string" => Type::String,
            "long" => Type::Long,
            "longlong" => Type::LongLong,
            "float" => Type::Float,
            "bool" => Type::Bool,
            _ => Type::Object(type_name.to_string()),
        }
    }
    //(a;b;c)
    fn parse_set_of_expression(&mut self) -> Option<Vec<Expression>> {
        let mut items: Vec<Expression> = Vec::new();
        while true {
            if self.try_next_token(TokenType::Semicolon) {
                continue;
            }
            if self.try_next_token(TokenType::FuncEnd) {
                break;
            }
            let item = self.parse()?;
            items.push(item);
        }
        Some(items)
    }
    //int[,,];
    fn parse_array_init(&mut self) -> Option<Expression> {
        let mut items: Vec<Expression> = Vec::new();
        while true {
            if self.try_next_token(TokenType::And) {
                continue;
            }
            if self.try_next_token(TokenType::ArrayEnd) {
                break;
            }
            let item = self.parse_primary()?;
            items.push(item);
        }
        Some(self.new_exp(ExpressionType::ArrayInit { exps: items }))
    }
    fn parse_call_parameter(&mut self) -> Option<Vec<Expression>> {
        let mut items: Vec<Expression> = Vec::new();
        while true {
            if self.try_next_token(TokenType::And) {
                continue;
            }
            if self.try_next_token(TokenType::FuncEnd) {
                break;
            }
            let item = self.parse_primary()?;
            items.push(item);
        }
        Some(items)
    }

    ///按顺序解析函数参数，如果顺序不对，则会解析失败，返回None
    fn parse_function_parameter(&mut self) -> Option<Vec<Parameter>> {
        let mut items: Vec<Parameter> = Vec::new();
        while true {
            if self.try_next_token(TokenType::And) {
                continue;
            }
            if self.try_next_token(TokenType::FuncEnd) {
                break;
            }

            let mut type_name: String = String::new();
            let mut var_name: String = String::new();
            let token = self.next_token()?;
            if let TokenType::VarType(result) = token.token_type {
                type_name = result;
            } else {
                self.push_err(format!("参数解析错误,非类型标识符 {:?}", token));
                return None;
            };

            let token = self.next_token()?;
            if let TokenType::Identifier(result) = token.token_type {
                var_name = result;
            } else {
                self.push_err(format!("参数解析错误,非预期标识符 {:?}", token));
                return None;
            };

            items.push(Parameter {
                var_type: Self::get_var_type(type_name.as_str()),
                var_name,
            });
        }
        Some(items)
    }
    /// 解析函数
    /// func void():abc
    fn parse_function(&mut self, func_name: String) -> Option<Expression> {
        let args = self.parse_function_parameter()?;
        let mut func_type: Type = Type::None;

        if self.try_next_token(TokenType::Colon) {
            let token = self.next_token()?;
            if let TokenType::VarType(result) = token.token_type {
                func_type = Self::get_var_type(result.as_str());
            } else if let TokenType::Identifier(result) = token.token_type {
                func_type = Self::get_var_type(result.as_str());
            } else {
                self.push_err(format!("函数解析错误,非预期标识符 {:?}", token));
                return None;
            }
        }
        let doc = self.get_doc();
        let body = self.parse()?;
        Some(self.new_exp(ExpressionType::Statement(Statement::Function {
            document: doc,
            func_name: Some(func_name),
            return_type: func_type,
            body: Box::new(body),
            args,
        })))
    }
    ///解析块
    fn parse_block(&mut self) -> Option<Expression> {
        let mut items: Vec<Expression> = Vec::new();
        while true {
            if self.try_next_token(TokenType::Semicolon) {
                continue;
            }
            if self.try_next_token(TokenType::BlockEnd) {
                break;
            }
            items.push(self.parse()?);
        }
        Some(self.new_exp(ExpressionType::Block { body: items }))
    }
    ///解析类型表达式
    fn parse_class(&mut self, class_name: &str) -> Option<Expression> {
        let doc = self.get_doc();
        let body = self.parse_block()?;
        Some(self.new_exp(ExpressionType::Statement(Statement::Class {
            document: doc,
            class_name: class_name.to_string(),
            member: Box::new(body),
        })))
    }
    //解析单个语句，并删除后面的;
    fn parse_single_expression(&mut self) -> Option<Expression> {
        let result = self.parse()?;
        if (self.try_next_token(TokenType::Semicolon)) {
            //这里不用写，尝试删除;
        }
        return Some(result);
    }
    ///while true {}
    fn parse_while(&mut self) -> Option<Expression> {
        let cond = self.parse()?;
        if self.try_next_token(TokenType::BlockBegin) {
            let body = self.parse_block()?;
            return Some(self.new_exp(ExpressionType::While {
                condition: Box::new(cond),
                body: Box::new(body),
            }));
        }
        self.push_err_str("while 解析错误,未知标识符");
        None
    }
    ///for(;;){}
    fn parse_for(&mut self) -> Option<Expression> {
        if self.try_next_token(TokenType::FuncBegin) {
            let init = self.parse_single_expression()?;
            let cond = self.parse_single_expression()?;
            let incr = self.parse_single_expression()?;
            if self.try_next_token(TokenType::FuncEnd) {
                if (self.try_next_token(TokenType::BlockBegin)) {
                    let body = self.parse_block()?;
                    let result = self.new_exp(ExpressionType::For {
                        init: Box::new(init),
                        condition: Box::new(cond),
                        increment: Box::new(incr),
                        body: Box::new(body),
                    });
                    return Some(result);
                }
                self.push_err_str("for解析错误,必须以代码块为主体");
            } else {
                self.push_err_str("for解析错误,括号未闭合");
            }
        }
        self.push_err_str("for解析错误,异常标识符");
        None
    }

    ///解析 if表达式，格式为 if xx {}<else>{}
    fn parse_if(&mut self) -> Option<Expression> {
        let condition = self.parse_primary()?;
        if self.try_next_token(TokenType::BlockBegin) {
            let then = self.parse_block()?;

            if self.try_next_token(TokenType::KeyWord(KeyWord::Else)) {
                if self.try_next_token(TokenType::BlockBegin) {
                    let not = self.parse_block()?;
                    return Some(self.new_exp(ExpressionType::If {
                        condition: Box::new(condition),
                        then: Box::new(then),
                        not: Some(Box::new(not)),
                    }));
                } else {
                    self.push_err("if表达式未使用{标识符".to_string());
                    return None;
                }
            } else {
                return Some(self.new_exp(ExpressionType::If {
                    condition: Box::new(condition),
                    then: Box::new(then),
                    not: None,
                }));
            }
        }
        self.push_err_str("if 表达式解析失败,格式错误");
        None
    }

    ///函数调用解析
    fn parse_call_function(
        &mut self,
        variable: Option<AccessTarget>,
        call_name: String,
    ) -> Option<Expression> {
        let call_args = self.parse_call_parameter()?;

        if let Some(result) = variable {
            Some(self.new_exp(ExpressionType::VariableRead {
                var_name: AccessTarget::Call {
                    func_name: call_name,
                    callee: Some(Box::new(result)),
                    args: call_args,
                },
            }))
        } else {
            Some(self.new_exp(ExpressionType::VariableRead {
                var_name: AccessTarget::Call {
                    func_name: call_name,
                    callee: None,
                    args: call_args,
                },
            }))
        }
    }

    ///尝试解析操作符
    fn try_parse_operator(&mut self, left: Expression) -> Option<Expression> {
        let mut root = left;
        //数学
        while let Some(now_priority) = self.try_get_next_token_is_operator() {
            root = self.try_parse_math_priority(root, now_priority)?;
        }
        //变量引用
        if self.try_next_token(TokenType::Dot) {
            let right = self.parse_primary()?;

            let result = self.new_exp(ExpressionType::VariableRead {
                var_name: AccessTarget::Field {
                    to: Box::new(right),
                    from: Box::new(root),
                },
            });

            return Some(result);
        }
        if let Some(result) = self.try_next_token_variant(TokenType::Compared(Compared::Equals)) {
            if let TokenType::Compared(result) = result.token_type {
                let right = self.parse()?;
                return Some(self.new_exp(ExpressionType::Compared {
                    left: Box::new(root),
                    compared: result,
                    right: Box::new(right),
                }));
            }
        }
        //如果没有操作符就原封不动的返回当前值
        Some(root)
    }
    ///尝试解析数学表达式
    fn try_parse_math_priority(
        &mut self,
        mut left: Expression,
        priority: u8,
    ) -> Option<Expression> {
        loop {
            if let Some(now_priority) = self.try_get_next_token_is_operator() {
                if now_priority < priority {
                    break;
                }
                let op = self.next_token()?;

                if let TokenType::Operator(result) = op.token_type {
                    let right = self.parse_primary()?;
                    let right = self.try_parse_math_priority(right, now_priority + 1)?;
                    left = self.new_exp(ExpressionType::Math {
                        left: Box::new(left),
                        operator: result,
                        right: Box::new(right),
                    });
                } else {
                    self.push_err_str("解析公式时遇到意外的错误");
                    break;
                }
            } else {
                break;
            }
        }
        Some(left)
    }
    ///解析复制符号右值表达式，且用Box封装
    fn parse_assignment_right_box_exp(&mut self) -> Option<Box<Expression>> {
        if self.try_next_token(TokenType::Operator(Operator::Assignment)) {
            let init = self.parse()?;
            Some(Box::new(init))
        } else {
            None
        }
    }
    ///变量初始化
    fn parse_variable_init(&mut self, type_name: String, var_name: String) -> Option<Expression> {
        let doc = self.get_doc();
        let var_type = Self::get_var_type(type_name.as_str());
        let init = self.parse_assignment_right_box_exp();
        Some(self.new_exp(ExpressionType::Statement(Statement::Variable {
            document: doc,
            var_type,
            var_name,
            var_init: init,
        })))
    }
    ///变量初始化
    ///int[] i=[0,0,0];
    fn parse_array_variable_init(
        &mut self,
        type_name: String,
        var_name: String,
        array_size: Option<i32>,
    ) -> Option<Expression> {
        let doc = self.get_doc();
        let base_type = Self::get_var_type(type_name.as_str());
        let var_type = Type::ArrayType {
            array_type: Box::new(base_type),
            array_size,
        };
        let init = self.parse_assignment_right_box_exp();
        Some(self.new_exp(ExpressionType::Statement(Statement::Variable {
            document: doc,
            var_type,
            var_name,
            var_init: init,
        })))
    }
    //i = 123;
    ///处理变量写入
    fn parse_variable_write(&mut self, type_name: String) -> Option<Expression> {
        if self.try_next_token(TokenType::Operator(Operator::Assignment)) {
            let result = self.parse_primary()?;
            return Some(self.new_exp(ExpressionType::VariableWrite {
                var_name: AccessTarget::Variable(type_name),
                result: Box::new(result),
            }));
        }
        self.push_err("变量初始化错误,非预期的标识符".to_string());
        None
    }

    ///一元表达式封装
    fn parse_monomial(&mut self, last_operator: Operator) -> Option<Expression> {
        let exp = self.parse_primary()?;
        Some(self.new_exp(ExpressionType::Monomial {
            operator: last_operator,
            value: Box::new(exp),
        }))
    }
    ///获取表达式
    fn new_exp(&self, expression_type: ExpressionType) -> Expression {
        Expression {
            line: self.last_token_line,
            row: self.last_token_row,
            exp_type: expression_type,
        }
    }
    fn get_doc(&mut self) -> Option<String> {
        if self.doc.len() == 0 {
            return None;
        }

        let mut doc = String::new();

        for item in &self.doc {
            doc.push_str(item);
        }
        self.doc.clear();
        Some(doc)
    }
    fn push_err(&mut self, text: String) {
        self.errors.push(ErrInfo {
            line: self.last_token_line,
            row: self.last_token_row,
            text,
        });
    }
    fn push_err_str(&mut self, text: &str) {
        self.errors.push(ErrInfo {
            line: self.last_token_line,
            row: self.last_token_row,
            text: text.to_string(),
        });
    }
    pub fn is_legal(&self) -> bool {
        if self.errors.len() > 0 {
            for error in &self.errors {
                println!(
                    "解析时错误 (line：{},row：{}):{}",
                    &error.line, &error.row, &error.text
                );
            }
            return false;
        }
        true
    }
    pub fn traverse_access_target(at: AccessTarget) {
        match at {
            AccessTarget::Field { to, from } => {
                Self::traverse(*to);
                Self::traverse(*from);
            }
            AccessTarget::Index { array, index } => {
                Self::traverse_access_target(*array);
                Self::traverse(*index);
            }

            AccessTarget::Call {
                callee,
                func_name,
                args,
            } => {
                if let Some(result) = callee {
                    Self::traverse_access_target(*result);
                }
                for item in args {
                    Self::traverse(item);
                }
            }

            _ => {
                return;
            }
        }
    }
    pub fn traverse(mut exp: Expression) {
        match exp.exp_type {
            ExpressionType::Block { body } => {
                for item in body {
                    Self::traverse(item);
                }
            }

            ExpressionType::If {
                condition,
                then,
                not,
            } => {
                Self::traverse(*condition);
                Self::traverse(*then);
                if let Some(not) = not {
                    Self::traverse(*not)
                }
            }

            ExpressionType::For {
                init,
                condition,
                increment,
                body,
            } => {
                Self::traverse(*init);
                Self::traverse(*condition);
                Self::traverse(*increment);
                Self::traverse(*body);
            }

            ExpressionType::While { condition, body } => {
                Self::traverse(*condition);
                Self::traverse(*body);
            }

            ExpressionType::Math {
                left,
                operator,
                right,
            } => {
                Self::traverse(*left);
                Self::traverse(*right);
            }

            ExpressionType::Compared {
                left,
                compared,
                right,
            } => {
                Self::traverse(*left);
                Self::traverse(*right);
            }

            ExpressionType::Monomial { operator, value } => {
                Self::traverse(*value);
            }

            ExpressionType::Return { value } => {
                if let Some(value) = value {
                    Self::traverse(*value)
                };
            }
            ExpressionType::VariableRead { var_name } => {}
            ExpressionType::Statement(statement) => match statement {
                Variable {
                    document,
                    var_name,
                    var_type,
                    var_init,
                } => {
                    if let Some(value) = var_init {
                        Self::traverse(*value)
                    };
                }
                Statement::Function {
                    document,
                    func_name,
                    return_type,
                    args,
                    body,
                } => {
                    Self::traverse(*body);
                }
                Statement::Class {
                    document,
                    class_name,
                    member,
                } => {
                    Self::traverse(*member);
                }

                _ => {
                    return;
                }
            },

            _ => {
                return;
            }
        }
    }
}
